using System;
using System.Data;
using System.IO;
using System.IO.Compression;

namespace Glpt.Data
{
    /// <summary>
    /// 数据集的加载及输出类
    /// </summary>
    public class DataSetIO
    {
        /// <summary>
        /// 把DataTable对象保存成二进制文件
        /// </summary>
        /// <param name="dt">数据集</param>
        /// <param name="filename">文件名</param>
        public static void SaveDataTableToXmlZip(DataTable dt, String filename)
        {
            if (dt.TableName.Length == 0) dt.TableName = "Table1";
            FileStream commstm = new FileStream(filename, FileMode.Create, FileAccess.Write);
            GZipStream compressedzipStream = new GZipStream(commstm, CompressionMode.Compress, true);
            dt.WriteXml(compressedzipStream, XmlWriteMode.WriteSchema);
            compressedzipStream.Close();
            commstm.Close();
        }

        /// <summary>
        /// 读取文件,返回DataTable对象
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns>数据集</returns>
        public static DataTable ReadDataTableFromXmlZip(String filename)
        {
            FileStream commstm = new FileStream(filename, FileMode.Open, FileAccess.Read);
            GZipStream zipStream = new GZipStream(commstm, CompressionMode.Decompress);
            DataTable dt = new DataTable();
            dt.ReadXml(zipStream);
            zipStream.Close();
            commstm.Close();
            return dt;
        }

        /// <summary>
        /// 把DataSet对象保存成二进制文件
        /// </summary>
        /// <param name="dset">数据集</param>
        /// <param name="filename">文件名</param>
        public static void SaveDataSetToXmlZip(DataSet dset, String filename)
        {
            FileStream commstm = new FileStream(filename, FileMode.Create, FileAccess.Write);
            GZipStream compressedzipStream = new GZipStream(commstm, CompressionMode.Compress, true);
            dset.WriteXml(compressedzipStream, XmlWriteMode.WriteSchema);
            compressedzipStream.Close();
            commstm.Close();
        }

        /// <summary>
        /// 读取文件,返回DataSet对象
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns>数据集</returns>
        public static DataSet ReadDataSetFromXmlZip(String filename)
        {
            FileStream commstm = new FileStream(filename, FileMode.Open, FileAccess.Read);
            GZipStream zipStream = new GZipStream(commstm, CompressionMode.Decompress);
            DataSet dset = new DataSet();
            dset.ReadXml(zipStream);
            zipStream.Close();
            commstm.Close();
            return dset;
        }
    }
}
